//
//  GoodPingJiaVC.m
//  QinghaiTourism
//
//  Created by QianXiaoShu on 16/3/31.
//  Copyright © 2016年 QianXiaoShu. All rights reserved.
//

#import "AllPingJiaVC.h"
#import "QHEvaObj.h"
#import "QHPingJiaObj.h"
#import "PingJIACELL.h"

@interface AllPingJiaVC ()<UITableViewDelegate,UITableViewDataSource,NSCacheDelegate>{
    BOOL isLastData;
    
}

@property(nonatomic,assign)int currentPage;

@property (nonatomic,strong)QHPingJiaObj *qhPingjiaObj;
@property (nonatomic,strong)QHEvaObj *evaObj;
@property (nonatomic,strong) UITableView *tableView;

// 缓存的容器
@property (nonatomic, strong) NSCache *imageCache;
@property (nonatomic,strong)NSMutableArray *datasource;
@property (nonatomic, strong) NSOperationQueue *opQueue;
/**所有下载的缓冲池*/
@property (nonatomic, strong) NSMutableDictionary *operationCache;

@end

@implementation AllPingJiaVC

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [self addInterface];
    
 
    __weak AllPingJiaVC *weakSelf = self;
    [self setLoadNewDataBlock:^{
        [weakSelf Pull];
        [weakSelf endRefresh];

    }];
    
    [self setLoadMoreDataBlock:^{
        [weakSelf load];
        [weakSelf endRefresh];
    
    }];
    NSLog(@"%@缓存路径:",[self cachePathWithUrl:@""]);
}

- (void)addInterface{

  [self.view addSubview:self.tableView];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self Pull];
}

/**
 拼接一个文件在沙盒的全路径
 */
-(NSString *)cachePathWithUrl:(NSString *)urlStr
{  // 将图片网址名作为作为最后一项
    // 1. 获得缓存的路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // 2. 把路径根urlStr拼接起来
    return [cachePath stringByAppendingPathComponent:urlStr.lastPathComponent];
}
#pragma marksetter and getter
-(NSOperationQueue *)opQueue
{
    if (_opQueue == nil) {
        _opQueue = [[NSOperationQueue alloc] init];
    }
    return _opQueue;
}
-(NSMutableDictionary *)operationCache
{
    if (_operationCache == nil) {
        _operationCache = [[NSMutableDictionary alloc] init];
    }
    return _operationCache;
}
- (NSMutableArray *)datasource{
   
    if (_datasource == nil) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                             
                                                             NSUserDomainMask, YES);
        NSString *path = [paths objectAtIndex:0];
        
        path = [path
                           
                           stringByAppendingPathComponent:@"MyAppCache"];
        //判断是否有缓存 缓存路径是否为真
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm fileExistsAtPath:path];
        
        if([fm fileExistsAtPath:path]){//如果为真 证明有缓存
            //读取缓存数据
            
            NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];
            // 字典转模型
            NSMutableArray *arryM = [NSMutableArray array];
            for(NSDictionary *dict in dicArray){
                QHEvaObj *app = [QHEvaObj appWithDict:dict];
                [arryM addObject:app];
            }
            _datasource = arryM;
        }else{
            _datasource =[ NSMutableArray array];
        }

    }

    return _datasource;

}
- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kWindowWidth, kWindowHeight-44) style:UITableViewStyleGrouped];
        
        _tableView.delegate = self;
        
        _tableView.dataSource = self;
        
    }
    return _tableView;
}

-(NSCache *)imageCache
{
    if (_imageCache == nil) {
        _imageCache = [[NSCache alloc] init];
        
        /**  NSCache类以下几个属性用于限制成本
         NSUInteger totalCostLimit  "成本" 限制，默认是0（没有限制）
         NSUInteger countLimit  数量的限制  默认是0 （没有限制）
         
         // 设置缓存的对象，同时指定限制成本
         -(void)setObject:(id) obj  forKey:(id) key cost:(NSUInteger) g
         */
        
        // 设置数量限额。一旦超出限额，会自动删除之前添加的东西
        _imageCache.countLimit = 30;  // 设置了存放对象的最大数量
        _imageCache.delegate = self;
    }
    return _imageCache;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (int i =0 ; i< 100; i++) {
        // 向缓存中添加对象
        NSString *str = [NSString stringWithFormat:@"hello - %d", i];
        [self.imageCache setObject:str forKey:@(i)]; // @(i) 相当于  [NSNumber numberWith......]
    }
    for (int i=0 ; i< 100; i++) {
        NSLog(@"%@", [self.imageCache objectForKey:@(i)]);
    }
}

-(void)cache:(NSCache *)cache willEvictObject:(id)obj
{
    // 此代理方法主要用于程序员的测试
    NSLog(@"要删除的对象obj-------------%@", obj);
}


-(void)Pull{
    self.currentPage = 1;
    
    [self requestFromServer];
    
}
-(void)load{
    if (!isLastData) {
        
        self.currentPage ++;
        isLastData = YES;
        
        [self requestFromServer];
        
    }
    
}

-(void)requestFromServer{
 NSString *pageIndexS = [NSString stringWithFormat:@"%d",self.currentPage];
    //grade:@""  --all
//#pragma mark测试 需要修改id
    [UserModuleApi getDrivePingJiaWithDeiverId:@"3" grade:@"" pageIndex:pageIndexS pageSize:@"20" completion:^(AIResult *result) {
        isLastData = NO;

        if (result.success) {
            NSLog(@"获取评价%@",result.object);
            
           
            _qhPingjiaObj = (QHPingJiaObj *)result.object;
            if (_qhPingjiaObj) {
               
                [[NSNotificationCenter defaultCenter]postNotificationName:@"PINGJIANUMBER" object:nil];
                

            }
            NSArray *temp = _qhPingjiaObj.eavList;
            [self dealDataSourceLoadOrPull:temp];

            
            NSLog(@"commentsEva%@",_qhPingjiaObj.commentsEva);
            NSLog(@"eavscore%@",_evaObj.eavscore);
            [_tableView reloadData];

        }else{
            
            [QHTools AlertControl:result.message];

        }
        
    
    }];
    
    
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    // 需要在这里做一些内存清理的工作，如果不处理会被系统强制闪退
    // 清理内存
    [self.imageCache  removeAllObjects];
    
    // 清理操作的缓存
    [self.operationCache removeAllObjects];
    
    // 取消下载队列内的任务
    [self.opQueue cancelAllOperations];
}

-(void)dealDataSourceLoadOrPull:(NSArray *)temp{
    
    if (self.currentPage == 1) {
        [_datasource removeAllObjects];
        
    }
    if (temp.count == 0) {
        
        self.currentPage --;
        if (self.currentPage <=1 ) {
            self.currentPage = 1;
        }
        return ;
    }
    [_datasource addObjectsFromArray:temp];
    
    
}


#pragma mark - <UITableViewDelegate,UITableViewDataSource>



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString *cellID = @"cell";
    
    PingJIACELL *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[PingJIACELL alloc]initWithStyle:UITableViewCellStyleSubtitle
                                 reuseIdentifier:cellID];
        
        
    }
    
    cell.evaObj = _datasource[indexPath.row];
  
    QHEvaObj *app = self.datasource[indexPath.row];
    // 判断模型里面是否有图像
    if ([self.imageCache objectForKey:app.headUrl]) { // 内存有图片
        NSLog(@" 图片已经下载......");
        //[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.headUrl] placeholderImage:nil];
        cell.imageView.image = [self.imageCache objectForKey:app.headUrl];

    }else{
        
        UIImage *image = [UIImage imageWithContentsOfFile:[self cachePathWithUrl:app.headUrl]];
        if (image) {   //  沙盒有图片
            NSLog(@"直接从沙盒加载图片");
            
            // 1. 设置图片缓存到内存，方便下次从内存直接加载
            [self.imageCache setObject:image forKey:app.headUrl];
            
            // 2. 显示图片到cell
            cell.imageView.image = [self.imageCache objectForKey:app.headUrl];
        }else{  // 沙盒没有图片
            
            // 显示图片—占位图
            cell.imageView.backgroundColor = [UIColor lightGrayColor];
            
            
            // 下载图片
            [self downloadImage:indexPath];
          //  [self Pull];

        }
    }
    cell.imageView.alpha = 0.2;

    return cell;
 
}

-(void)downloadImage:(NSIndexPath *)indexPath
{
    QHEvaObj *app = self.datasource[indexPath.row];
   
    if (self.operationCache[app.headUrl]) {
        NSLog(@"正在玩命下载中......");
        return;
    }
    // 缓冲池没有下载操作
    
    // 异步下载图片
    __weak typeof(self) weakSelf = self;
    NSBlockOperation  *downLoadOp = [NSBlockOperation blockOperationWithBlock:^{
        // 模拟延时
        [NSThread sleepForTimeInterval:2];
        NSLog(@"正在下载中......");
        
        //  1. 下载图片（二进制数据）
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.headUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        //  2. 将下载的数据保存到沙盒
        // 字典的赋值不能为nil,赋值为nil会崩溃
        if (image) {
            // 先保存到图片缓存
            [weakSelf.imageCache setObject:image forKey:app.headUrl];
            
            // 将图片写入到沙盒
            [data writeToFile:[self cachePathWithUrl:app.headUrl] atomically:YES];
        }
        
        // 3 将操作从缓冲池删除——将下载好的图片操作从缓冲池中移除
        [weakSelf.operationCache removeObjectForKey:app.headUrl];
        
        //  4. 在主线程更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            /** reload 会重新调用cell的初始化方法, 会重新判断模型里面是否有图像
             有的话就直接显示
             */
        }];
    }];
    
    // 将操作添加到队列
    [weakSelf.opQueue addOperation:downLoadOp];
    NSLog(@"操作的数量------------->%ld", self.opQueue.operationCount);
    
    // 将操作添加到缓冲池中(使用图片的url作为key)
    [weakSelf.operationCache setObject:downLoadOp forKey:app.headUrl];
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.datasource.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // [self.navigationController pushViewController:[[DetailLawyer alloc] init] animated:YES];
    NSLog(@"%@", self.operationCache);

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    PingJIACELL *cell = (PingJIACELL *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
//    NSLog(@"高度~~~~~~~~~~~~~~~~~~~~~~》%f",[QHTools heightForText:cell.titleLabel.text]);
//    
//    return 120;
//   // return [PingJIACELL rowHeight];
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:kWindowWidth tableView:tableView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */



@end
